<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>

<body>
    <h1>创建axios实例</h1>
    <button>提交</button>


    <script>
        const oBtn = document.querySelector("button")
        const myAxios = axios.create({
            baseURL: "/1",
            timeout: 10000,
            headers: {}
        })

        myAxios.interceptors.request.use(config => {
            console.log(config);
            alert("请求拦截器")
            return config //一定要放行
        }, err => {
            return Promise.reject(err.message)
        })


        // 设置axios的响应拦截
        myAxios.interceptors.response.use(res => {
            console.log(res); //拿到的是响应的结果
            alert("响应拦截器")
            return res.data.data //放行  可以修改返回的数据
        }, err => {
            return Promise.reject(err.message) //如果异常返回一个失败的promise实例传递给 下面的分支（catch）
        })


        oBtn.onclick = async function () {
            try {
                const result = await myAxios.get("/user", {
                    params: {
                        userId: "001"
                    }
                })
                console.log(result);
            } catch (e) {
                console.log(e); //接收到响应拦截中的异常信息，并打印
            }
        }
    </script>
</body>

</html>